﻿//Copyright (c) 2008 Michael J. Ryan & Apollo Group, Inc.

//Permission is hereby granted, free of charge, to any person
//obtaining a copy of this software and associated documentation
//files (the "Software"), to deal in the Software without
//restriction, including without limitation the rights to use,
//copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the
//Software is furnished to do so, subject to the following
//conditions:

//The above copyright notice and this permission notice shall be
//included in all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
//EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
//OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
//NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
//HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
//WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
//FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
//OTHER DEALINGS IN THE SOFTWARE.

using System;
using System.Configuration;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Apollo.Common.Cache
{
	public static class MC
	{
	
#region Private Member Variables
		private static MemcachedClient _mc;
#endregion
	
#region Constructor
		/// <summary>
		/// Static constructor, initialize the internal memcached client reference.
		/// </summary>
		static MC()
		{
			LogAdapter log = LogAdapter.GetLogger(typeof(MC));
			
			try 
			{	        
				log.Info("Loading configuration.");
				
				//get list of memcached servers.
				string cfg = ConfigurationManager.AppSettings["memcached_servers"] ?? "";
				List<string> servers = new List<string>();
				foreach (string s in cfg.Split(';')) {
					string sv = s.Trim();
					if (!string.IsNullOrEmpty(sv))
					{
						servers.Add(sv);
					}
				}
				
				if (servers == null || servers.Count == 0)
					throw new ConfigurationErrorsException("Apollo.Common.Cache 'memcached_servers' not defined in application config file.");
				
				MemcachedClient.Setup("Apollo.Common.Cache", servers.ToArray());
				_mc = MemcachedClient.GetInstance("Apollo.Common.Cache");
				_mc.MaxPoolSize = (uint)32;
				_mc.MinPoolSize = (uint)8;
			}
			catch (Exception err)
			{
				//log as a fatal exception.
				LogAdapter.GetLogger(typeof(MC)).Fatal("Apollo.Common.Cache.MC configuration exception.", err);
				
				//rethrow exception
				throw;
			}
		}
#endregion

#region Public Static Properties
	#region Client
		public static MemcachedClient Client
		{
			get { return _mc; }
		}
	#endregion
#endregion

	}
}
